import { Slave } from 'message-lite';
import { ALL_SERVICE } from './impl';

export const slave = new Slave({
  createSender(data: any) {
    return (message) => {
      window.parent!.postMessage(message, '*', []);
    };
  },
  listenMessage(fn) {
    window.addEventListener('message', fn, false);
  },
  unListenMessage(fn: (message: any) => void): void {
    window.removeEventListener('message', fn, false);
  },
  transformMessage(message: MessageEvent) {
    return message.data;
  },
}).addService(ALL_SERVICE);

export function slaveBootstrap() {
  if (window.parent !== window) {
    return slave.connect();
  }
  return Promise.resolve();
}
